package com.lc.midi.mid;


import com.lc.midi.keyEvent.KeyEvents;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MidiTrack {
	/*
	 * track head
	 */
	private final static String MTrk = "MTrk";
	private int len;
	/*
	 * track body
	 */
	private List<MidiEvent> midiEvents = new ArrayList<MidiEvent>();
	
	public List<MidiEvent> getMidiEvents(){
		return midiEvents;
	}
	
	public int read(MidiFile midifile) throws IOException, MidiException {
		byte[] tmp = new byte[4];
		int ret = midifile.read(tmp);
		if (!ByteConvert.btoStr(tmp).equals(MTrk)) {
			throw new MidiException("track head is not MTrk");
		}
		ret = midifile.read(tmp);
		len = ByteConvert.btoInt(tmp);
		int total = 0;
		int tlen = 0;
		while(total < len) {
			MidiEvent midiEvent = new MidiEvent();
			tlen = midiEvent.read(midifile);
			if (tlen == -1)//音轨结束
				break;
			total += tlen;
			midiEvents.add(midiEvent);
		}
		return 4 + 4 + len;
	}
	
	public List<Byte> write(KeyEvents keyEvents, MidiOutFile outFile){
		List<Byte> bytes = new ArrayList<Byte>();
		bytes.addAll(ByteConvert.strTob(MTrk));
		return null;//TO DO
	}
}
